package com.molichuxing.gateway.bff.payment.services.impl;

import com.alibaba.fastjson.JSONObject;
import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.utils.DingTalkUtil;
import com.molichuxing.gateway.bff.payment.services.AlipayBffService;
import com.molichuxing.services.business.dto.response.NotifyBizDto;
import com.molichuxing.services.business.service.PaymentBizService;
import com.molichuxing.services.property.PaymentChannelEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 支付宝支付bff
 * 
 * @author zoumingyu
 * @date 2019年10月29日
 *
 */
@Service("alipayBffService")
public class AlipayBffServiceImpl implements AlipayBffService {
	private static final Logger logger = LoggerFactory.getLogger(WechatpayBffServiceImpl.class);

	@Value("${profiles.active}")
	private String active;

	@Value("${profiles.active.explain}")
	private String activeExplain;

	@Resource
	private PaymentBizService paymentBizService;

	/**
	 * 支付宝支付回调结果
	 * 
	 * @param aliParams
	 * @return
	 * @throws Exception
	 */
	@Override
	public NotifyBizDto modifyNotifyPay(Map<String, String[]> aliParams) throws Exception {
		logger.info("[modifyNotifyPay]支付宝支付回调:{}", aliParams);
		NotifyBizDto result = null;
		// 验证并修改支付单信息
		try {
			// 用以存放转化后的参数集合
			Map<String, String> conversionParams = new HashMap<String, String>();
			for (Iterator<String> iter = aliParams.keySet().iterator(); iter.hasNext();) {
				String key = iter.next();
				String[] values = aliParams.get(key);
				String valueStr = "";
				for (int i = 0; i < values.length; i++) {
					valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
				}
				// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
				// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "uft-8");
				conversionParams.put(key, valueStr);
			}
			logger.info("[modifyNotifyPay]支付宝返回参数集合：({})", conversionParams);
			result = paymentBizService.modifyNotify(conversionParams, PaymentChannelEnum.ALIPAY);
			logger.info("[modifyNotifyPay]支付宝支付修改结果：" + JSONObject.toJSONString(result));
		} catch (BizException e) {
			if (e.getExceptionCode() != null && e.getExceptionCode() == 110) {
				throw e;
			} else {
				logger.error("[modifyNotifyPay]支付宝支付回调异常:", e);
				DingTalkUtil.exceptionSend(activeExplain + "支付宝支付回调异常：" + e.getMessage());
				throw e;
			}
		} catch (Exception e) {
			logger.error("[modifyNotifyPay]支付宝支付回调异常:", e);
			DingTalkUtil.exceptionSend(activeExplain + "支付宝支付回调异常：" + e.getMessage());
			throw e;
		}
		return result;

	}

}
